<?php
class GoodsTagsModel extends MongoModel{
	var $table ='goods_tags';
	var $name = '商品标签';
	
	private static $_static_models = array();
	/**
	 * @return MongoModel
	 */
	public static function model(){
		if(version_compare(PHP_VERSION,'5.3',">")){
			$className = get_called_class();
		}else{
			throw new CException('MongoModel::model() 必须在php 5.3及以上版本才支持!');
		}
		if(isset(self::$_static_models[$className])){
			return self::$_static_models[$className];
		}
		$mod = new $className;
		self::$_static_models[$className] = $mod;
		return $mod;
	}
	
	public static $COLOR = array(
		'#EEA500',
		'#815B22',
		'#0549F9',
		'#9E0623',
		'#2D9EE7',
		'#D40476',
		'#A6C500',
		'#6700FF',
		'#66AB00',
		'#1E8B00',
		'#755E8C',
		'#6F8760',
		'#F56B00',
		'#F072D6',
		'#E01C00',
		'#773B3D',
		'#66768A',
		'#26ABAB',
		'#A600FF',
		'#D7C300'
	);
	
	public static $RECOMMEND_TAGS = array(
		'推荐', '新品', '热销', '特价', '促销'
	);
	
	private static $c_id = null;
	public static function getColor(){
		while(true){
			$k = array_rand(self::$COLOR);
			if(self::$c_id != $k)
				break;
		}
		self::$c_id = $k;
		return self::$COLOR[$k];
	} 
	
	/**
	 * 获取前？个热门标签
	 * @param unknown $store_id
	 * @param string $has_null
	 * @param string $null_text
	 * @param number $count
	 * @return array
	 */
	public static function getTagOpts($store_id, $has_null = true, $null_text = '所有标签', $count = 20){
		$con = array();
		if(is_array($store_id)){
			$con['store_id'] = array('$in' => $store_id);
		}else{
			$con['store_id'] = $store_id;
		}
		$tags = GoodsTagsModel::model()->find($con, 'name,count', 0, $count, array('count'=>-1));
		$opts = array();
		if($has_null){
			$opts[''] = $null_text;
		}
		if(!empty($tags)){
			foreach ($tags as $tag){
				$opts[$tag['name']] = "{$tag['name']} ({$tag['count']})";
			}
		}
		return $opts;
	}
	
	public static function addTag($tag, $store_goods_id, $store_id){
		$mod = GoodsTagsModel::model();
		$tag_doc = $mod->get_by_attrs(array(
			'store_id' 		=> $store_id,
			'name' 			=> $tag,
		), '_id');
		if(empty($tag_doc)){
			$tag_data = array(
				'_id' 			=> CommonHelper::gen_uuid(),
				'count' 		=> 1,
				'store_id' 		=> $store_id,
				'name' 			=> $tag,
			);
			$mod->insert($tag_data);
		}else{
			$_id = $tag_doc['_id'];
			$mod->update(array('_id'=>$_id), array(
				'$inc' => array('count' => 1)
			), array(
				'multiple' => false
			));
		}
	}
	
	public static function delTag($tag, $store_goods_id, $store_id){
		$mod = GoodsTagsModel::model();
		$tag_doc = $mod->get_by_attrs(array(
			'store_id' 		=> $store_id,
			'name' 			=> $tag,
		), '_id,count');
		if(!empty($tag_doc)){
			$count = intval($tag_doc['count']);
			$_id = $tag_doc['_id'];
			if($count == 1){
				//删除
				$mod->delete_by_key($_id);
			}else{
				//扣减
				$mod->update(array('_id'=>$_id), array(
					'$inc' => array('count' => -1)
				), array(
					'multiple' => false
				));
			}
		}
	}
}
?>